package com.dex4d.ui.dapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.model.User;
import com.dex4d.ui.dapp.model.DappTrade;
import com.dex4d.ui.demo.HomeActivity;
import com.wallet.web3.entity.Web3Transaction;

import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;

public class ConfirmationActivity extends AppToolBarBaseActivity implements DappTrade.OnTransferListener {

    public static void open(Activity activity, Web3Transaction transaction, String url) {
        Intent intent = new Intent(activity, ConfirmationActivity.class);
        intent.putExtra("TX", transaction);
        intent.putExtra("URL", url);
        activity.startActivityForResult(intent, HomeActivity.REQUEST_CODE_DAPP);
    }

    @BindView(R.id.text_from)
    TextView fromAddressText;
    @BindView(R.id.text_to)
    TextView toAddressText;
    @BindView(R.id.text_value)
    TextView valueText;
    @BindView(R.id.text_gas_price)
    TextView gasPriceText;
    @BindView(R.id.text_gas_limit)
    TextView gasLimitText;
    @BindView(R.id.text_network_fee)
    TextView networkFeeText;
    @BindView(R.id.text_contract)
    TextView contractAddrText;
    @BindView(R.id.label_contract)
    TextView contractAddrLabel;
    @BindView(R.id.label_website)
    TextView websiteLabel;
    @BindView(R.id.text_website)
    TextView websiteText;
    @BindView(R.id.send_button)
    Button sendButton;

    @BindView(R.id.label_amount)
    TextView labelAmount;

    @BindView(R.id.text_total_fee)
    TextView text_total_fee;

    Web3Transaction transaction;

    DappTrade dappTrade;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_confirmation;
    }

    @Override
    protected void initVariables() {

        transaction = getIntent().getParcelableExtra("TX");
        dappTrade = new DappTrade(this, this);
        dappTrade.setTransaction(transaction);

        parsePayload(transaction.payload);

        String toAddress = transaction.recipient.toString();

        if (transaction.contract != null) {
            contractAddrText.setVisibility(View.VISIBLE);
            contractAddrLabel.setVisibility(View.VISIBLE);
            contractAddrText.setText(transaction.contract.toString());
        } else {
            BigInteger addr = Numeric.toBigInt(transaction.recipient.toString());
            if (addr.equals(BigInteger.ZERO)) //constructor
            {
                toAddress = getString(R.string.ticket_contract_constructor);
            }
        }

        fromAddressText.setText(User.getInstance().getAddress());
        toAddressText.setText(toAddress);

        String urlRequester = getIntent().getStringExtra("URL");

        if (!TextUtils.isEmpty(urlRequester)) {
            websiteLabel.setVisibility(View.VISIBLE);
            websiteText.setVisibility(View.VISIBLE);
            websiteText.setText(urlRequester);
        }

        BigDecimal ethAmount = Convert.fromWei(transaction.value.toString(10), Convert.Unit.ETHER);
        String amountString = getEthString(ethAmount.doubleValue()) + " " + "ETH";

        valueText.setText(amountString);

        BigDecimal gasPrice = Convert.fromWei(transaction.gasPrice.toString(10), Convert.Unit.ETHER);
        gasPriceText.setText(getEthString(gasPrice.doubleValue()));

        gasLimitText.setText(transaction.gasLimit.toString());

        BigDecimal networkFee = Convert.fromWei(transaction.gasPrice.multiply(transaction.gasLimit).toString(10), Convert.Unit.ETHER);
        networkFeeText.setText(getEthString(networkFee.doubleValue()));

        text_total_fee.setText(String.format(getResources().getString(R.string.label_total), getEthString(ethAmount.add(networkFee).doubleValue())));

    }

    private void parsePayload(String data) {

        String payload = Numeric.cleanHexPrefix(data);

        String name = payload.substring(0, 8);
        String inputs = payload.substring(8, payload.length());

    }

    public String getEthString(double ethPrice) {
        DecimalFormat df = new DecimalFormat("#.#####");
        df.setRoundingMode(RoundingMode.CEILING);
        String formatted = df.format(ethPrice);
        return formatted;
    }

    @Override
    protected void loadData() {
//        dappTrade.estimateGas(transaction.payload,transaction.recipient.toString(),transaction.value);
    }

    @Override
    protected void initToolbar() {
        showDappBackView(transaction);
        showTitle(getResources().getString(R.string.confirm_transfer_details));
    }

    @OnClick(R.id.send_button)
    public void signWeb3DAppTransaction() {
        //TODO 不需要确认页面
//        Intent intent = new Intent();
//        intent.putExtra("TX", transaction);
//        setResult(RESULT_OK, intent);
//        finish();

//        需要确认页面
        dappTrade.trade();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //TODO 监听返回键
        Intent intent = new Intent();
        intent.putExtra("TX", transaction);
        intent.putExtra("SIGNED", false);
        setResult(RESULT_OK, intent);
        finish();
    }


    @Override
    public void success(Web3Transaction transaction, String result) {
        DappDoneActivity.start(this, transaction, result);
        finish();
    }

    @Override
    public void error(Web3Transaction transaction, String result) {

    }
}


